using System;
using System.Text.Json;
using CommunityToolkit.Mvvm.ComponentModel;
using mas.Models;

namespace mas.ViewModels;

public partial class MessageDetailViewModel : ViewModelBase, IDisposable
{
    private readonly HeaderData _headerData;  // 持有原始HeaderData引用
    
    [ObservableProperty] private string _formattedMessage;

    public MessageDetailViewModel(HeaderData headerData)
    {
        _headerData = headerData;
        _formattedMessage = FormatJson(headerData.Message);
        
        // 监听原始数据变化
        _headerData.PropertyChanged += OnHeaderDataPropertyChanged;
    }

    // 响应HeaderData属性变化
    private void OnHeaderDataPropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(HeaderData.Message))
        {
            FormattedMessage = FormatJson(_headerData.Message);  // 重新格式化并更新消息
        }
    }

    // JSON格式化逻辑
    private string FormatJson(string json)
    {
        try
        {
            var jsonElement = JsonDocument.Parse(json).RootElement;
            return JsonSerializer.Serialize(jsonElement, new JsonSerializerOptions { WriteIndented = true });
        }
        catch
        {
            return $"JSON格式化失败：\n{json}";
        }
    }

    // 释放资源（取消订阅避免内存泄漏）
    public void Dispose()
    {
        _headerData.PropertyChanged -= OnHeaderDataPropertyChanged;
    }
}